package com.lagou.balance;

import com.alibaba.fastjson.JSONObject;
import com.lagou.handler.UserClientHandler;
import com.lagou.stat.RequestInfo;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;

import java.util.List;

public class ShortTimeBalance implements Balance {

    private static final String STAT = "/stat";

    private CuratorFramework curatorFramework;

    public ShortTimeBalance(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
    }

    @Override
    public UserClientHandler choose(List<UserClientHandler> list) throws Exception {
        long bestTime = Long.MAX_VALUE;
        UserClientHandler bestHandler = null;
        for (UserClientHandler userClientHandler : list) {
            String address = userClientHandler.getAddress();
            String path = String.format("%s/%s/%s", STAT, userClientHandler.getRpcRequest().getClass().getSimpleName(), address);
            Stat stat = curatorFramework.checkExists().forPath(path);
            if (stat != null) {
                byte[] bytes = curatorFramework.getData().forPath(path);
                RequestInfo requestInfo = JSONObject.parseObject(bytes, RequestInfo.class);
                if (requestInfo.getLastUseTime() < bestTime) {
                    bestTime = requestInfo.getLastUseTime();
                    bestHandler = userClientHandler;
                }
            }
        }
        if (bestHandler == null) {
            bestHandler = list.get(0);
        }
        return bestHandler;
    }
}
